package com.doghome.testsecurity.securityhandler;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Component
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private RedisTemplate<Object,Object> redisTemplate;


    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        logger.debug("登录成功："+authentication);
        Map<String,Object> map = new HashMap<>();
        map.put("AuthToken",authentication);
        String token = UUID.randomUUID().toString();
        logger.debug("生成token:"+token);
        map.put("time",System.currentTimeMillis());
        map.put("token",token);
        logger.debug("缓存身份认证数据");
        redisTemplate.opsForValue().set(token,map,30, TimeUnit.MINUTES);


        Map<String,Object> rs = new HashMap<>();
        rs.put("message","ok");
        rs.put("token", token);
        rs.put("userName",authentication.getPrincipal());

        ObjectMapper om = new ObjectMapper();

        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        response.getWriter().write(om.writeValueAsString(rs));
        response.getWriter().flush();
        response.getWriter().close();
    }
}
